package com.onlyxiahui.app.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通用程序的上下文，用于管理整个程序对象管理<br>
 * 和模块之间的桥梁 date 2017-09-20 3:22:56
 * 
 * @author XiaHui
 */
public class AppContext {

	private final ObjectFactory objectFactory = new ObjectFactory(this);
	private final Map<Class<?>, AbstractFactory> factoryMap = new ConcurrentHashMap<>();

	/**
	 * 放入已经实例化的对象
	 * 
	 * @author XiaHui
	 * @param defineClass
	 * @param object
	 */
	public <T> void put(Class<T> defineClass, T object) {
		objectFactory.put(defineClass, object);
	}

	/**
	 * 注册接口或者父类所对应的实现子类，当根据类型获取对象时就会获取此实现类的实例
	 * 
	 * @author XiaHui
	 * @param defineClass：父类或者接口
	 * @param instanceClass：实现子类
	 */
	public <T> void register(Class<T> defineClass, Class<? extends T> instanceClass) {
		objectFactory.register(defineClass, instanceClass);
	}

	public <T> T getObject(Class<T> classType) {
		return getObject(classType, false, false);
	}

	public <T> T getObject(Class<T> classType, boolean createNew) {
		return getObject(classType, createNew, false);
	}

	public <T> T getObject(Class<T> classType, boolean createNew, boolean cover) {
		T t = null;
		for (AbstractFactory af : factoryMap.values()) {
			if (af.isSupport(classType)) {
				t = af.getObject(classType, createNew, cover);
				break;
			}
		}
		if (null == t) {
			t = objectFactory.getObject(classType, createNew, cover);
		}
		return t;
	}

	public <T> T createObject(Class<T> classType) {
		return objectFactory.createObject(classType);
	}

	public ObjectFactory getObjectFactory() {
		return objectFactory;
	}

	public <T extends AbstractFactory> void putFactory(Class<T> clazz) {
		if (null != clazz) {
			AbstractFactory af = this.createObject(clazz);
			factoryMap.put(clazz, af);
		}
	}
}
